import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Plan } from 'src/schemas/plan.schema';
import CreatePlanDto from './dto/create.plan.dto';
import UpdatePlanDto from './dto/update.plan.dto';

@Injectable()
export class PlanService {
  constructor(@InjectModel(Plan.name) private planModel: Model<Plan>) {}

  private formatPlan(plan) {
    return {
      ...plan,
      motions: plan.motions.map((motion) => {
        const motionData: any = { ...motion };
        motionData.name = motionData.motionId.name;
        motionData.group = motionData.motionId.group;
        motionData.category = motionData.motionId.category;
        motionData.tool = motionData.motionId.tool;
        motionData.img = motionData.motionId.img;
        motionData.openInner = motionData.innerRest !== 0;
        motionData.openOuter = motionData.outerRest !== 0;
        motionData.motionId = motionData.motionId._id;
        return motionData;
      }),
    };
  }

  async createPlan(userId: string, dto: CreatePlanDto) {
    return await this.planModel.create({
      ...dto,
      userId,
    });
  }
  async getPlan(planId: string) {
    const plan = await this.planModel
      .findById(planId)
      .populate({
        path: 'motions.motionId',
        select: 'name group category tool img',
      })
      .lean();
    return this.formatPlan(plan);
  }

  async getPlans(userId: string) {
    const plans = await this.planModel
      .find({ userId })
      .populate({
        path: 'motions.motionId',
        select: 'name group category tool img',
      })
      .lean();

    return plans.map(this.formatPlan);
  }

  async updatePlan(planId: string, dto: UpdatePlanDto) {
    return await this.planModel.findByIdAndUpdate(planId, dto);
  }

  async deletePlan(planId) {
    return await this.planModel.findByIdAndDelete(planId);
  }
}
